/*
 * RecordUpdateHandler.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.gerengdic.dictionary;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import de.studiorutton.gerengdic.dictionary.records.LeftRightValuesRecord;

class RecordUpdateHandler extends Handler implements IRecordsUpdateListener {
	private final static String TAG = "learningwords";
	private DictionaryAdapter da;
	private IDictionaryView dv;
	private Dictionary d;

	private final static int NOTIFY_START = 0;
	private final static int NOTIFY_NEW_RECORD = 1;
	private final static int NOTIFY_ERROR = 2;
	private final static int NOTIFY_DONE = 3;
	private final static int NOTIFY_CANCELLED = 4;
	private final static int NOTIFY_PROGRESS = 5;

	public RecordUpdateHandler(IDictionaryView dv, DictionaryAdapter da, Dictionary d) {
		super();
		this.da = da;
		this.dv = dv;
		this.d = d;
	}
	
	public void setDictionaryView( IDictionaryView dv ) {
		this.dv = dv;
	}
	
	public void notifyStart() {
		Message msg = Message.obtain(this);
		msg.what = NOTIFY_START;
		sendMessage( msg );
	}

	public void notifyNewRecord(LeftRightValuesRecord record) {
		Message msg = Message.obtain(this);
		msg.what = NOTIFY_NEW_RECORD;
		msg.obj = record;
		sendMessage(msg);
	}

	public void notifyError(String error) {
		Message msg = Message.obtain(this);
		msg.what = NOTIFY_ERROR;
		msg.obj = error;
		sendMessage(msg);
	}

	public void notifyDone(int status ) {
		Message msg = Message.obtain(this);
		if ( status == DictionaryWorker.DONE_CANCELLED)
			msg.what = NOTIFY_CANCELLED;
		else
			msg.what = NOTIFY_DONE;
		sendMessage(msg);
	}
	
	public void notifyProgress() {
		Message msg = Message.obtain(this);
		msg.what = NOTIFY_PROGRESS;
		sendMessage(msg);
	}

	public void handleMessage(Message msg) {
		// Log.d( TAG, "RecordUpdateHandler: handleMessage." );
		switch (msg.what) {
		case NOTIFY_START:
			dv.updateProgressBar( true );
			da.setIsLoadingData( true, true );
			break;
		case NOTIFY_NEW_RECORD:
			LeftRightValuesRecord lrvr = (LeftRightValuesRecord) msg.obj;
			DictionaryRecordContent drc = new DictionaryRecordContent( lrvr.getMinErrors(), lrvr );
			da.addItem(drc, true);
			if ( da.getCount() == 3 )
				d.addHistoryEntry();
			break;
		case NOTIFY_ERROR:
			String error = (String) msg.obj;
			dv.updateProgressBar( false );
			da.setIsLoadingData(false, true );
			dv.showErrorDialog(error);
			break;
		case NOTIFY_DONE:
			dv.updateProgressBar( false );
			da.setIsLoadingData(false, true );
			d.addHistoryEntry();
			break;
		case NOTIFY_CANCELLED:
			dv.updateProgressBar( false );
			da.setIsLoadingData(false, true );
			break;
		case NOTIFY_PROGRESS:
			da.notifyDataSetChanged();
		}
		
	}

	
}
